import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtDrawer} from "taro-ui"
import {Block, Image, Swiper, SwiperItem, View} from '@tarojs/components'
import Skeleton from 'taro-skeleton'
import {TARO_ENV} from "../../constants/api"
import {
  getHeadTop,
  gotoPage,
  vcmonitor,
  getStorageSync,
  setStorageSync
} from "../../utils/tools"
import CityLocation from "../../components/city-location/city-location"
import SiteLocation from "../../components/site-location/site-location"
import MainMenu from '../../components/main-menu/main-menu'
import {platform} from "../../utils/platform-settting.service"
import {location as locationServer} from "../../utils/location.service"
import {
  getSiteMode,
  getSiteList,
  getMenuButtonBoundingClientRect,
  getBanner,
  getIndexDiy
} from '../../utils/getCommonData'
import {handlerIndexH5Share, handlerIndexPublicCode} from "../../utils/handlerPublicCode";
import './big.scss'
import CustomTabBar from "../../components/tabBar/tab-bar";

type typeState = {
  banners: any
  tabBarInfo: any
  headTop: any
  locations: any
  showLoading: any
  platformSet: any
  siteList: any
  indexDiy: any
  multiSite: any
  show: any
  menuInfo: any
}

export default class Big extends Component {
  state: typeState = {
    banners: false,
    tabBarInfo: false,
    platformSet: {},
    showLoading: true,
    multiSite: 0,
    show: false,
    menuInfo: {},
    siteList: [],
    locations: {area_name: '全国'},
    indexDiy: false,
    headTop: false,
  }

  async UNSAFE_componentWillMount() {
    if (process.env.P_ENV !== 'vc' && process.env.P_ENV !== 'kunxin') {
      return false
    }
    let sKey = getStorageSync('sKey') || '';
    let siteList: any = []
    const siteMode = await getSiteMode()
    if (siteMode) {
      siteList = await getSiteList()
      const storageSKey = getStorageSync('sKey')
      const query: any = this.instance.router.params;
      if (query.skey) {
        sKey = query.skey
      } else if (storageSKey) {
        sKey = storageSKey
      }
      if (!sKey) {
        sKey = siteList[0] && siteList[0].uuid
        setStorageSync('sKey', sKey);
        if (TARO_ENV === 'weapp') {
          const platformSet: any = platform.getPlatFormSet()
          if (platformSet) {
            platform.info = platformSet
          }
        } else {
          return window.location.reload()
        }
      } else {
        setStorageSync('sKey', sKey);
      }
    }
    const menuInfo = getMenuButtonBoundingClientRect()
    this.setState({siteList, menuInfo, multiSite: !!siteMode})
  }

  async componentDidShow() {
    await vcmonitor(this)
    await locationServer.autoLocation()
    await this.handlerDidShow()
  }

  async handlerDidShow() {
    const isH5 = TARO_ENV === 'h5'
    const pageObj = this.instance.page
    let tabbar
    if (process.env.TARO_ENV === 'weapp') {
      tabbar = Taro.getTabBar(pageObj)
    }
    platform.getIndexNavigation().then(res => {
      if (res) {
        const tabBarInfo = JSON.parse(res)
        const pagePath = pageObj.route
        if (process.env.TARO_ENV === 'weapp') {
          tabbar.setState({ tabBarInfo, pagePath, isBigIndexPage: tabBarInfo.list.length >= 5 })
        } else {
          this.setState({ tabBarInfo })
        }
      }
    })
    const platformSet = await platform.info
    this.platformLogo = platform.info.platformLogo
    this.platformName = platform.info.platformName
    const {scene, tempSellerId = '', bindSellerId} = this.instance.router.params
    this.shareParam = await handlerIndexPublicCode(platformSet, scene, tempSellerId, bindSellerId)
    if (isH5) {
      await handlerIndexH5Share(this.platformName, '首页', '/pages/index/big', this.platformLogo, this.shareParam)
    }
    const banners: any = await getBanner({style: 1})
    const indexDiy: any = await getIndexDiy({style: 1})
    if ((banners.length <= 0 && indexDiy && indexDiy.menusRight.length <= 0 && indexDiy.menusUp.length <= 0) || (process.env.P_ENV !== 'vc' && process.env.P_ENV !== 'kunxin')) {
      const url = '/pages/index/index'
      if (isH5) {
        return window.location.replace(window.location.origin + url + window.location.search)
      } else {
        return Taro.switchTab({url})
      }
    }
    const headTop = getHeadTop() || {statusBar: 0, top: 12}
    this.setState({
      indexDiy,
      banners,
      headTop,
      platformSet: await platform.info,
      locations: getStorageSync('city') || {area_name: '全国'}
    }, async () => {
      this.setState({showLoading: false})
    })
  }

  async menusClick(item) {
    await gotoPage(item.link)
  }

  async setSKey(uuid) {
    const {siteList} = this.state
    let site: any
    for (const _i in siteList) {
      let _site
      if (siteList.hasOwnProperty(_i)) {
        _site = siteList[_i]
      }
      const _uuid = _site.uuid;
      if (uuid === _uuid) {
        site = _site;
      }
    }
    const sKey = site.uuid;
    const extConfig = getStorageSync('user');
    if (extConfig) {
      extConfig.mpkey = site.mpkey
      setStorageSync('user', extConfig)
    }
    setStorageSync('sKey', sKey);
    if (TARO_ENV === 'h5') {
      return window.location.replace(site.domains + '?mpkey=' + site.mpkey)
    } else {
      await this.handlerDidShow()
      const platformSet: any = await platform.getPlatFormSet()
      platform.info = platformSet
      this.setState({
        platformSet,
        show: false
      })
    }
  }

  showSite(show = true) {
    this.setState({show})
  }

  onShareAppMessage() {
    return {
      imgUrl: this.platformLogo,
      title: this.platformName,
      path: '/pages/index/big?' + this.shareParam + `&sKey=${getStorageSync('sKey')}`
    }
  }

  onShareTimeline() {
    return {
      imgUrl: this.platformLogo,
      title: this.platformName,
      query: '?' + this.shareParam + `&sKey=${getStorageSync('sKey')}`
    }
  }

  shareParam: any = ''
  instance: any = Taro.getCurrentInstance()
  platformLogo: any = ''
  platformName: any = ''
  citySiteConfig = {
    cityFont: '12px',
    cityColor: '#fff',
    searchFont: '12px',
    searchColor: '#fff',
    separationLine: false,
    customClass: 'bigPageClass',
    placeholderText: '景区/酒店/商品',
  }

  render() {
    const {banners, headTop, showLoading, locations, indexDiy, show, siteList, menuInfo, platformSet, multiSite, tabBarInfo} = this.state
    return (
      <View className='bigIndexRoot'>
        <Skeleton loading={showLoading}
          title
          titleWidth='100%' rowHeight='258px'
        >
          <Block>
            {tabBarInfo && <View style='position: fixed; width: 100%; z-index: 9999; bottom: 0px; left: 0;'><CustomTabBar pagePath='pages/index/big' isBigIndexPage={tabBarInfo.list.length >= 5} tabBarInfo={tabBarInfo} /></View>}
            {indexDiy && indexDiy.menusUp && indexDiy.menusUp.length > 0 && <View className='headerMenusWrapper'>
              <MainMenu customClass='headerMenusBox' offsetTop={headTop.top + headTop.statusBar + 45} index={5}
                data={indexDiy.menusUp}
              />
            </View>}
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading}
          title
          titleWidth='100%' rowHeight='258px'
        >
          <Block>
            {banners && banners.length > 0 && <Swiper
              autoplay={banners.length > 1}
              className='big-index-banner-wrapper'
            >
              {banners.map((item, index) => <SwiperItem className='banner-item' key={index}
                onClick={this.menusClick.bind(this, item, index)}
              >
                <Image className='big-index-banner' src={item.img} mode='aspectFill' />
              </SwiperItem>)}
            </Swiper>}
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading}
          title
          titleWidth='100%' rowHeight='258px'
        >
          <View className={`search-bar ${TARO_ENV + 'search-bar'}`}
            style={`top: ${headTop.top + headTop.statusBar}px;`}
          >
            {!multiSite && <CityLocation {...this.citySiteConfig} locations={locations} />}
            {!!multiSite &&
            <SiteLocation {...this.citySiteConfig} platformSet={platformSet} onShow={() => this.showSite()} />}
          </View>
        </Skeleton>
        <Skeleton loading={showLoading}
          title
          titleWidth='100%' rowHeight='258px'
        >
          <Block>
            {indexDiy && indexDiy.menusRight && indexDiy.menusRight.length > 0 && <View className='rightMenusWrapper'>
              <MainMenu customClass='bigIndexClass' data={indexDiy.menusRight} />
            </View>}
          </Block>
        </Skeleton>
        <AtDrawer
          show={show}
          mask
          onClose={() => this.showSite(false)}
        >
          {
            !showLoading && siteList.map((item, index) =>
              <View
                key={index}
                style={`margin-top: ${(index === 0) && (menuInfo.top - 10)}px`}
                className={`drawer-item ${item.label === (platformSet.platformName || '') && 'drawer-item-active'}`}
                onClick={() => this.setSKey(item.uuid)}
              >
                {item.label}
              </View>
            )
          }
        </AtDrawer>
      </View>
    )
  }
}
